<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input
          v-model="treeData.keyword"
          style="margin-bottom:10px"
          type="text"
          prefix-icon="el-icon-search"
          size="small"
          placeholder="输入员工姓名全员搜索"
          @input="inputChange"
        />
        <!-- 树形组件 -->
        <el-tree
          ref="treeData"
          :data="depts"
          :props="defaultProps"
          default-expand-all
          highlight-current
          :expand-on-click-node="false"
          node-key="id"
          @current-change="selectTreeNode"
        />
      </div>
      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <el-button v-permission="'add-employee'" size="mini" type="primary" @click="$router.push('/employee/detail')">添加员工</el-button>
          <el-button v-permission="'import'" size="mini" @click="showExcelDialog = true">excel导入</el-button>
          <el-button size="mini" @click="exportExcel">excel导出</el-button>
        </el-row>
        <!-- 表格组件 -->
        <el-table :data="treeDataList">
          <el-table-column prop="staffPhoto" label="头像" align="center">
            <template #default="{row}">
              <template v-if="row.staffPhoto">
                <el-avatar :size="30" :src="row.staffPhoto" />
              </template>

              <template v-else>
                <!-- <span> <el-avatar style="background-color: #00cdbf;" :size="30"> {{ row.username?.charAt(0) }} </el-avatar></span> -->
                <span class="username">{{ row.username?.charAt(0) }}</span>
              </template>
            </template>
          </el-table-column>

          <el-table-column prop="username" label="姓名" />
          <el-table-column prop="mobile" label="手机号" sortable />
          <el-table-column prop="formOfEmployment" label="聘用形式">
            <template #default="{row}">
              {{ row.formOfEmployment === 1 ? '正式': (row.formOfEmployment === 2 ? '非正式' :'无') }}
            </template>
          </el-table-column>

          <el-table-column prop="departmentName" label="部门" />
          <el-table-column prop="timeOfEntry" label="入职时间" sortable />
          <el-table-column label="操作" width="120px">
            <template #default="{row}">
              <el-button type="text" size="mini" @click="$router.push(`/employee/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="mini" @click="roleBtn(row.id)">角色</el-button>
              <el-popconfirm

                confirm-button-text="好的"
                cancel-button-text="再想想"
                icon="el-icon-info"
                icon-color="red"
                title="你确定删除该员工吗?"
                @onConfirm="delok(row.id)"
              >
                <el-button slot="reference" type="text" size="mini" style="margin-left: 5px;">删除</el-button>
              </el-popconfirm>
            </template>
          </el-table-column>

        </el-table>
        <!-- 分页 -->
        <el-row type="flex" justify="end" align="middle" style="height: 60px;">
          <el-pagination
            layout="total,sizes,prev, pager, next"
            :total="total"
            :page-size="treeData.pagesize"
            :current-page="treeData.page"
            :page-sizes="[5, 10, 20, 50]"
            @current-change="changeCurrentPage"
            @size-change="handleSizeChange"
          />
        </el-row>
      </div>
    </div>
    <ExportExcel :show-excel-dialog.sync="showExcelDialog" @uploadSuccess="getEmployeeList" />
    <!-- 角色弹层 -->
    <el-dialog title="角色列表" :visible.sync="showRoleDialog">
      <el-checkbox-group v-model="checkList">
        <el-checkbox v-for="item in roleList" :key="item.id" :label="item.id">{{ item.name }}</el-checkbox>
      </el-checkbox-group>

      <el-row slot="footer" type="flex" justify="center" align="middle">
        <el-col :span="6">
          <el-button size="mini" type="primary" @click="updateRoleOk">确定</el-button>
          <el-button size="mini" @click="showRoleDialog=false">取消</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import { getDepartmentList } from '@/api/department'
import { queryListBytree } from '@/utils'
import { getEmployeeList, exportEmpDataByExcel, delEmployee, getRoleList, getEmployeeDetail, updateEmpRole } from '@/api/employee'
import fileSaver from 'file-saver'
import _ from 'lodash'
import ExportExcel from '@/views/employee/components/export-excel.vue'
export default {
  name: 'Employee',
  components: {
    ExportExcel
  },
  data() {
    return {
      depts: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      total: 0,
      treeData: {
        departmentId: null,
        page: 1,
        pagesize: 10,
        keyword: ''
      },
      treeDataList: [],
      showExcelDialog: false,
      showRoleDialog: false,
      checkList: [],
      roleList: [],
      roleId: null
    }
  },
  created() {
    this.getDepartmentList()
  },
  methods: {
    // 删除
    async delok(id) {
      try {
        await delEmployee(id)

        if (this.treeData.page > 1 && this.treeDataList.length === 1) {
          this.treeData.page--
        }
        this.getEmployeeList()
        this.$message.success('删除成功')
      } catch (error) {
        this.$message.error('删除失败')
      }
    },
    async getDepartmentList() {
      this.depts = queryListBytree(await getDepartmentList(), 0)
      // 获取根节点的id并默认选中
      this.treeData.departmentId = this.depts[0].id
      this.$nextTick(() => {
        this.$refs.treeData.setCurrentKey(this.depts[0].id)
      })
      this.getEmployeeList(this.treeData)
    },
    selectTreeNode(node) {
      this.treeData.departmentId = node.id
      this.treeData.page = 1
      this.getEmployeeList(this.treeData)
    },
    async getEmployeeList() {
      const { rows, total } = await getEmployeeList(this.treeData)
      this.treeDataList = rows
      this.total = total
    },
    changeCurrentPage(newPage) {
      this.treeData.page = newPage
      this.getEmployeeList()
    },
    handleSizeChange(value) {
      this.treeData.pagesize = value
      this.getEmployeeList()
    },
    // 模糊查询
    // 使用lodash库实现
    inputChange:
      _.debounce(function() {
        this.treeData.page = 1
        this.getEmployeeList()
      }, 600),

    async exportExcel() {
      try {
        const res = await exportEmpDataByExcel()
        fileSaver.saveAs(res, '员工信息表.xlsx')
        this.$message.success('导出员工信息表成功')
      } catch (error) {
        this.$message.error('导出员工信息表失败')
      }
    },
    async roleBtn(id) {
      // 角色列表
      this.roleList = await getRoleList()
      // 已分配角色
      this.roleId = id
      const { roleIds } = await getEmployeeDetail(id)
      this.checkList = roleIds
      this.showRoleDialog = true
    },
    async updateRoleOk() {
      await updateEmpRole({
        id: this.roleId,
        roleIds: this.checkList
      })
      this.showRoleDialog = false
      this.$message.success('修改员工角色成功')
    }

  }
}
</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;
  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }
  .right {
    flex: 1;
    padding: 20px;
    .opeate-tools {
      margin:10px ;
    }
    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04C9BE;
      font-size: 12px;
      display:inline-block;
    }
  }
}

</style>
